 <template>
  <d2-container>
    <template slot="header">
      <el-form :inline="true" :model="listQuery" size="mini" style="margin-bottom: -18px;">
        <el-form-item>
          <el-button type="primary" icon="el-icon-plus" @click="handleCreate">新 建</el-button>
        </el-form-item>
        <el-form-item label="搜索" prop="username">
          <el-input
            @keyup.enter.native="handleFilter"
            style="width: 200px;"
            placeholder=""
            v-model="listQuery.username"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="default" @click="handleFilter" icon="el-icon-search">搜 索</el-button>
        </el-form-item>
      </el-form>
    </template>
    <!-- table表格 -->
    <el-table
      :key="tableKey"
      :data="list"
      highlight-current-row
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" align="center" label="序号" width="60"></el-table-column>
      <el-table-column align="center" label="名称" width="250">
        <template slot-scope="scope">
          <span>{{scope.row.achievementName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="月份">
        <template slot-scope="scope">
          <span>{{scope.row.achievementdate | parseTime('{y}-{m}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="业务员级别" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.userName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="月业绩">
        <template slot-scope="scope">
          <span>{{scope.row.achievementmonth}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注">
        <template slot-scope="scope">
          <span>{{scope.row.note}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.createdate | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.modificationdate | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150" fixed="right">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="success"
            @click="handleDetial(scope.row)"
            icon="fa fa-bar-chart"
          ></el-button>-->
          <el-button
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
            icon="el-icon-edit"
          ></el-button>
          <el-button
            size="mini"
            type="danger"
            @click="deletes(scope.row)"
            icon="el-icon-delete"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- footer 分页条 -->
    <template slot="footer">
      <el-pagination
        background=""
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.page"
        :page-sizes="[50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: -10px;"
      ></el-pagination>
    </template>
    <!-- 新增 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-row style="width:100%">
          <el-col :span="20">
            <el-form-item label="月份" placeholder="" prop="carNo">
              <el-date-picker v-model="form.achievementdate" type="date" placeholder="选择年月" value-format="yyyy-MM-dd" format="yyyy-MM"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="名称" placeholder="" prop="vehicleNo">
              <el-input v-model="form.achievementName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="业务员级别" placeholder="" prop="carNo">
          <el-select v-model="form.achievementtype" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-row>
          <el-col :span="20">
            <el-form-item label="日业绩" placeholder="" prop="vehicleNo">
              <el-input v-model="form.achievementDay"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="周业绩" placeholder="" prop="vehicleNo">
              <el-input v-model="form.achievementWeek"></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="20">
            <el-form-item label="月业绩" placeholder="" prop="vehicleNo">
              <el-input v-model="form.achievementmonth"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="备注" placeholder="" prop="engineNumber">
              <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="form.note"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')" icon="el-icon-close" size="mini">取 消</el-button>
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          @click="create('form')"
          icon="el-icon-check"
          size="mini"
        >确 定</el-button>
        <el-button
          v-else
          type="primary"
          @click="update('form')"
          icon="el-icon-check"
          size="mini"
        >修 改</el-button>
      </div>
    </el-dialog>
  </d2-container>
</template>

<script>
import * as bizachievement from "@/api/bizachievement";
import { deptRoleList, fetchDeptTree } from "@/api/role";
import { mapGetters, mapState } from "vuex";
import ElRadioGroup from "element-ui/packages/radio/src/radio-group";
import ElOption from "element-ui/packages/select/src/option";
// Import component
import Loading from "vue-loading-overlay";
// Import stylesheet
import "vue-loading-overlay/dist/vue-loading.css";

import { getAassignList } from "@/api/customer";
import * as dict from "@/api/newcomer";

export default {
  components: {
    ElOption,
    ElRadioGroup,
    Loading
  },
  name: "table_user",
  data() {
    return {
      multipleSelection: [],
      options: [],
      value: "",

      table: {
        columns: [],
        data: [],
        size: "mini",
        stripe: true,
        border: true
      },

      isLoading: false,

      list: null,
      total: null,
      listQuery: {
        page: 1,
        limit: 50
      },
      form: {
        id: null,
        achievementdate: undefined,
        achievementName: undefined,
        achievementtype: undefined,
        achievementmonth: undefined,
        note: undefined,
      },
      rules: {},
      statusOptions: ["0", "1"],
      rolesOptions: [],
      dialogFormVisible: false,
      dialogDetailVisible: false,
      dialogDeptVisible: false,
      dialogImportExcelVisible: false,
      dialogAssignVisible: false,
      userAdd: false,
      userUpd: false,
      userDel: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "新增"
      },
      isDisabled: {
        0: false,
        1: true
      },
      tableKey: 0
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        import: "导入数据",
        allot: "分配数据"
      };
      return statusMap[status];
    }
  },
  computed: {
    // ...mapGetters(['permissions']),
    ...mapState("d2admin/user", ["info"])
  },
  created() {
    this.getList();

    dict.queryDictListByType("achievementType").then(resp => {
      console.log(resp);
      this.options = resp.records;
    });
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    handleNodeClick(data) {
      console.log(data);
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ name: "region1" }, { name: "region2" }]);
      }
      if (node.level > 3) return resolve([]);

      var hasChild;
      if (node.data.name === "region1") {
        hasChild = true;
      } else if (node.data.name === "region2") {
        hasChild = false;
      } else {
        hasChild = Math.random() > 0.5;
      }

      setTimeout(() => {
        var data;
        if (hasChild) {
          data = [
            {
              name: "zone" + this.count++
            },
            {
              name: "zone" + this.count++
            }
          ];
        } else {
          data = [];
        }

        resolve(data);
      }, 500);
    },

    getList() {
      this.isLoading = true;
      this.listQuery.isAsc = false;

      bizachievement.fetchList(this.listQuery).then(response => {
        this.list = response.records;
        this.total = response.total;
        this.isLoading = false;
      });
    },

    getNodeData(data) {
      this.dialogDeptVisible = false;
      this.form.deptId = data.id;
      this.form.deptName = data.name;
      deptRoleList(data.id).then(response => {
        this.rolesOptions = response;
      });
    },
    handleDept() {
      fetchDeptTree().then(response => {
        this.treeDeptData = response;
        this.dialogDeptVisible = true;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      // deptRoleList(this.info.deptId).then(response => {
      //   this.rolesOptions = response.data
      // })
    },
    handleAssign() {
      if (this.value == "") {
        this.$message({
          type: "error",
          message: "请选择分配对象"
        });
        return;
      }

      if (this.multipleSelection.length > 1) {
        this.$message({
          type: "error",
          message: "只能选择一个批次操作"
        });
        return;
      }

      this.$confirm("确认分配么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        batch
          .batchAssign({
            batchid: this.multipleSelection[0].batchNo,
            userId: this.value
          })
          .then(resp => {
            console.log(resp);
          });
      });
    },

    handleUpdate(row) {
      this.form = row;
      this.dialogFormVisible = true;
      this.dialogStatus = "update";
    },

    create(formName) {
      const set = this.$refs;

      set[formName].validate(valid => {
        if (valid) {
          let obj = this.options.find(item =>{
              return item.value === this.form.achievementtype;
          });
          this.form.achievementName = this.form.achievementName + "-" + obj.label;

          bizachievement.addObj(this.form).then(() => {
            // this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },

    cancel(formName) {
      this.dialogFormVisible = false;
      this.dialogAssignVisible = false;
      this.$refs[formName].resetFields();
    },

    update(formName) {
      const set = this.$refs;
      // this.form.role = this.role
      console.log(this.form);
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false;
          bizachievement.putObj(this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },

    deletes(row) {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        bizachievement.delObj(row.id).then(resp => {
          if (resp.status == "SUCCEED") {
            this.getList();
            this.$notify({
              title: "提示",
              message: "操作成功",
              type: "success"
            });
          } else {
            this.$notify({
              title: "提示",
              message: resp.errorMessage,
              type: "error"
            });
          }
        });
      });
    },

    handleDetial(row) {
      this.$router.push({
        path: "/newcomer/detail",
        query: { obj: row }
      });
    },

    resetTemp() {
      this.form = {
        id: undefined,
        catalogId: undefined,
        question: undefined,
        answer: undefined
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.d2-mb {
  float: left;
  margin-right: 20px;
}
.d2-mb .el-button i {
  margin-right: 4px;
}
</style>
